package com.guaoran.distributed.message.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author : guaoran
 * @Description : <br/>
 *  多个消费者消费 消息
 *  服务端,sub/pub ，订阅消息：类似群发消息,
 *  发布的消息是根当前时间有相关性，
 *  如果在发送消息前，消费者已经存在，则可以正常接收消息，
 *  如果在发现消息后，消费者才存在，则在存在前的消息将被忽略
 * @date :2018/11/8 14:53
 */
public class JMSTopicConsumer {
    public static void main(String[] args) throws JMSException {
        ConnectionFactory connectionFactory =
                new ActiveMQConnectionFactory(CommonUtil.CONNECT_URL);
        Connection connection = null;
        try {
            //创建连接
            connection = connectionFactory.createConnection();
            connection.start();
            //创建session会话
            Session session = connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
            //创建目的地
            Topic topic = session.createTopic("myTopic");
            //创建消息发送者
            MessageConsumer consumer = session.createConsumer(topic);
            //用来接收消息
            TextMessage message = (TextMessage) consumer.receive();//如果当前没有消息，则会进行阻塞
            System.out.println(message.getText());
            session.commit();
            session.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }finally {
            if(connection != null){
                connection.close();
            }
        }
    }
}
